# -*- coding: utf-8 -*-
# @Author : Yuan
from django.contrib.auth.models import Permission, ContentType, Group
from apps.users.models import User
from rest_framework import serializers


class PermissionModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Permission
        fields = '__all__'


class ContentTypeModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = ContentType
        fields = ['id', 'name']


class GroupModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Group
        fields = '__all__'


class AdminUserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            'password': {
                'write_only': True,
                'required': False
            }
        }

    def create(self, validated_data):
        user = super().create(validated_data)
        user.set_password(validated_data.get('password'))
        user.is_staff = True
        user.save()
        return user

    def update(self, instance, validated_data):
        super().update(instance, validated_data)
        password = validated_data.get('password')
        if password:
            instance.set_password(password)
            instance.save()
        return instance




